<template>
  <component v-model="selectValue" :is="selectComponent" :selector="selector" v-bind="$attrs" v-on="$attrs" :hookChange="hookChange">
    <template #option="{ option, index }">
      <slot name="option" :option="option" :index="index"></slot>
    </template>
    <template #label="{ data }">
      <slot name="label" :data="data"></slot>
    </template>
  </component>
</template>

<script setup name="remote-select">
  import OnceSelect from './remote-once-select.vue'
  import EachSelect from './remote-each-select.vue'
  import MultipleSelect from './remote-multiple-select.vue'
  import selectorConfig from './configs'
  import { useVModel } from '@vueuse/core'

  const props = defineProps({
    type: String,
    modelValue: [String, Number, Array],
  })

  const emit = defineEmits(['update:modelValue'])
  const selectValue = useVModel(props, 'modelValue', emit)

  const clearValue = () => {
    selectValue.value = undefined
  }

  // hook配置
  const hookChange = {
    change: () => {},
  }

  defineExpose({
    clearValue,
    hookChange,
  })

  // 初始化selector before
  const selector = selectorConfig[props.type]
  if (selector.key == null) selector.key = 'id'

  // 判断使用那个组件
  const mode = selector.mode || 'each'
  let selectComponent
  if (mode == 'once') {
    selectComponent = OnceSelect
  } else if (mode == 'multiple') {
    selectComponent = MultipleSelect
  } else {
    selectComponent = EachSelect
  }
</script>
